package org.jdpf.gui.rcp.neteditor.core.util;

import java.util.Stack;

import org.eclipse.swt.graphics.Point;
import org.jdpf.gui.rcp.neteditor.core.blocks.IGraphicBlock;
import org.jdpf.gui.rcp.neteditor.core.elements.GraphicNet;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GraphicNetParserEventHandler extends DefaultHandler{

	private String currentTransId;
	private String currentX, currentY;
	private GraphicNet gnet;
	private Stack<String> elementStack;
	
	public GraphicNetParserEventHandler(GraphicNet gnet) {
		this.gnet = gnet;
		elementStack = new Stack<String>();
	}

	@Override
	public void endDocument() throws SAXException {
		//no op
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String lastElement = elementStack.lastElement();
		if(lastElement.equals("x")){
			currentX = new String(ch, start, length);	
		} else if(lastElement.equals("y")){
			currentY = new String(ch, start, length);
		}
	}

	@Override
	public void startDocument() throws SAXException {
		//no op
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		String lastElement = elementStack.pop();
		if(lastElement.equals("Transition") || lastElement.equals("Inspector")){
			IGraphicBlock block = gnet.getBlock(currentTransId);
			int x = Integer.parseInt(currentX);
			int y = Integer.parseInt(currentY);
			block.setPosition(new Point(x, y));
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		elementStack.push(localName);
		if(localName.equals("Transition") || localName.equals("Inspector")){
			currentTransId = attributes.getValue("id");
		}
	}

}
